package com.ywt.tools;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.Settings;
import android.view.KeyEvent;
import android.widget.Toast;

import com.ywt.model.AreasModel;
import com.ywt.model.ChannelsModel;
import com.ywt.model.ConfigModel;
import com.ywt.model.LoginModel;
import com.ywt.ui.CustomProgressDialog;
import com.ywt.utils.Utils;

public class Action {
	private CustomProgressDialog progressDialog = null;

	static Context ctx;

	public Action(Activity activity) {
		ctx = activity;
	}

	/**
	 * <P>
	 * cookie
	 * </P>
	 */
	public String getCookie(Context ctxs) {
		// return Thinksns.getInstance(ctxs).getCookie();
		return null;
	}

	/**
	 * <P>
	 * cookie
	 * </P>
	 */
	public String getToken(Context ctxs) {
		// return Thinksns.getInstance(ctxs).getToken();
		return null;
	}

	OnKeyListener l = new OnKeyListener() {
		@Override
		public boolean onKey(DialogInterface arg0, int arg1, KeyEvent arg2) {
			if (arg2.getKeyCode() == 4) {
				return true;
			}
			return false;
		}
	};

	// 弹出是否退出应用对话框
	public static void exit(final Activity mCtx) {
		AlertDialog.Builder builder = new Builder(mCtx);
		builder.setTitle("提示")
				.setMessage("确定退出？")
				.setPositiveButton("确定",
						new android.content.DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog,
									int which) {
								Utils. cm  = null;
								Utils.  areaModels  = null;
								Utils.  channelModels  = null; 
								Utils.  loginModes  = null;
								mCtx.finish();
							}
						}).setNegativeButton("取消", null).show();

	}

	/**
	 * 查询手机内所有应用
	 * 
	 * @param context
	 * @return
	 */
	public static List<PackageInfo> getAllApps(Context context) {
		/**
		 * 
		 //set Icon
		 * shareItem.setIcon(pManager.getApplicationIcon(pinfo.applicationInfo
		 * )); //set Application Name
		 * shareItem.setLabel(pManager.getApplicationLabel
		 * (pinfo.applicationInfo).toString()); //set Package Name
		 * shareItem.setPackageName(pinfo.applicationInfo.packageName);
		 */
		PackageManager packageManager = context.getPackageManager();
		// final List<ResolveInfo> apps =
		// packageManager.queryIntentActivities(mainIntent, 0);
		List<PackageInfo> packageInfoList = packageManager
				.getInstalledPackages(0);
		return packageInfoList;
	}

	/**
	 * 获取系统所有的应用程序
	 * 
	 * @param context
	 * @return
	 */
	public static List<ResolveInfo> getAllMainApps(Context context) {
		final PackageManager packageManager = context.getPackageManager();
		final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
		mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
		// get all apps
		List<ResolveInfo> apps = packageManager.queryIntentActivities(
				mainIntent, 0);
		return apps;
	}

	/**
	 * 查询手机内非系统应用
	 * 
	 * @param context
	 * @return
	 */
	public static List<PackageInfo> getAlLNotSysApps(Context context) {
		/**
		 * 
		 // PackageInfo p = apps.get(i); //// Log.e("",
		 * String.valueOf(pManager.getApplicationIcon(p.applicationInfo))); //
		 * // Intent intent=new Intent(); //// Log.e("lable",
		 * pManager.getApplicationLabel(p.applicationInfo).toString()); // try {
		 * // if
		 * (manager.getApplicationLabel(p.applicationInfo).toString().contains
		 * ("京东商城")) { // Log.e("lable",
		 * String.valueOf(manager.getApplicationLabel
		 * (p.applicationInfo).toString())); // Log.e("pacagename",
		 * String.valueOf(p.applicationInfo.packageName.toString())); // intent
		 * =manager.getLaunchIntentForPackage(manager.getApplicationLabel(p.
		 * applicationInfo).toString()); //
		 * intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //
		 * mCtx.startActivity(intent); // } // Toast.makeText(mCtx,
		 * "Package not found1!", Toast.LENGTH_SHORT).show(); // } catch
		 * (ActivityNotFoundException noFound) { // Toast.makeText(mCtx,
		 * "Package not found2!", Toast.LENGTH_SHORT).show(); // }
		 */

		List<PackageInfo> apps = new ArrayList<PackageInfo>();
		PackageManager pManager = context.getPackageManager();
		// 获取手机内所有应用
		List<PackageInfo> paklist = pManager.getInstalledPackages(0);
		for (int i = 0; i < paklist.size(); i++) {
			PackageInfo pak = (PackageInfo) paklist.get(i);
			// 判断是否为非系统预装的应用程序
			if ((pak.applicationInfo.flags & pak.applicationInfo.FLAG_SYSTEM) <= 0) {
				// customs applications
				apps.add(pak);
			}
		}
		return apps;
	}

	/**
	 * 查询手机内系统应用
	 * 
	 * @param context
	 * @return
	 */
	public static List<PackageInfo> getAllSysApps(Context context) {

		List<PackageInfo> apps = new ArrayList<PackageInfo>();
		PackageManager pManager = context.getPackageManager();
		// 获取手机内所有应用
		List<PackageInfo> paklist = pManager.getInstalledPackages(0);
		for (int i = 0; i < paklist.size(); i++) {
			PackageInfo pak = (PackageInfo) paklist.get(i);
			// 判断是否为非系统预装的应用程序
			if ((pak.applicationInfo.flags & pak.applicationInfo.FLAG_SYSTEM) > 0) {
				// customs applications
				apps.add(pak);
			}
		}
		return apps;
	}

	/**
	 * <P>
	 * 进度提示调用开始
	 * </P>
	 */
	public void startProgressDialog(Context context) {

		if (context != null && progressDialog != null) {

			progressDialog = CustomProgressDialog.createDialog(context);
			progressDialog.setMessage("加载中");

			progressDialog.show();
		} else if (context != null && progressDialog == null) {

			progressDialog = CustomProgressDialog.createDialog(context);
			progressDialog.setMessage("加载中");

			progressDialog.show();
		}
	}

	/**
	 * <P>
	 * 进度提示调用开始
	 * </P>
	 */
	public void startProgressDialog(Context context, String msg) {
		if (progressDialog == null) {
			progressDialog = CustomProgressDialog.createDialog(context);
			if (msg != null) {
				progressDialog.setMessage(msg);
			} else {
				progressDialog.setMessage("加载中...");
			}
		}

		if (context != null) {
			progressDialog.show();
		}

	}

	/**
	 * <P>
	 * 进度提示调用取消
	 * </P>
	 */
	public void stopProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}

	public void showLongToast(String str) {
		Toast.makeText(ctx, str, Toast.LENGTH_LONG).show();
	}

	public void showShortToast(String str) {
		Toast.makeText(ctx, str, Toast.LENGTH_SHORT).show();
	}

	public Bitmap getBitmapFromUrl(String imgUrl) {
		URL url;
		Bitmap bitmap = null;
		try {
			url = new URL(imgUrl);
			InputStream is = url.openConnection().getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);
			bitmap = BitmapFactory.decodeStream(bis);
			bis.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bitmap;
	}

	public static boolean isNetworkAvailable(Context ctx) {
		Context context = ctx;
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
			// Error
		} else {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}

	// 判断网络是否可以用，并弹出设置网络对话框
	public static boolean NetWorkStatus(final Activity act) {
		boolean netSataus = false;
		ConnectivityManager cwjManager = (ConnectivityManager) act
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		cwjManager.getActiveNetworkInfo();
		if (cwjManager.getActiveNetworkInfo() != null) {
			netSataus = cwjManager.getActiveNetworkInfo().isAvailable();
		}
		if (!netSataus) {
			Builder b = new AlertDialog.Builder(act).setTitle("网络检查")
					.setMessage("请对网络进行设置");

			b.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					Intent mIntent = new Intent(
							Settings.ACTION_WIRELESS_SETTINGS);
					act.startActivity(mIntent); // 如果在设置完成后需要再次进行操作，可以重写操作代码，在这里不再重写

					// act.startActivityForResult(mIntent, 0); //
					// 如果在设置完成后需要再次进行操作，可以重写操作代码，在这里不再重写
				}

			}).setNegativeButton("退出", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					act.finish();
				}
			}).show();
		}
		return netSataus;
	} 
	
	public LoginModel LoginAction(String userName,String password) {
		LoginModel model = null;
		try {// 测试通过
	 
			String str = GetData.login(userName, password);
		 
			JSONObject json = new JSONObject(str);
//			System.out.println("1>>配置文件>>2>>" + "\n" + json);
			if (json != null) {
				if (json.getString("resCode").equals("1")) {
					model = new LoginModel();
					model.setUsername(json.getString("Username"));
					model.setExpireDate(json.getString("ExpireDate"));
					model.setAccessKey(json.getString("AccessKey"));
					model.setErrorInfo(json.getString("ErrorInfo"));
					model.setSubscription(json.getString("Subscription"));
					 
				}
			}
		
		} catch (Exception e) {
			System.out.println("登陆异常异常信息>>>>" + "\n" + e.getMessage());
			return null;
		}

		return model;
	}
	
	
	public ConfigModel getConfig() {
		ConfigModel model = null;
		try {// 测试通过
	 
			String str = GetData.getConfig();
		 
			JSONObject json = new JSONObject(str);
//			System.out.println("1>>配置文件>>2>>" + "\n" + json);
			if (json != null) {
				if (json.getString("resCode").equals("1")) {
					model = new ConfigModel();
					model.setArea_code(json.getString("area_code"));
					model.setChannel_code(json.getString("channel_code"));
					model.setNewstype_code(json.getString("newstype_code"));
					model.setNewtype_code(json.getString("newtype_code"));
					model.setVER_CODE(json.getString("version_code"));
					model.setVER_PATH(json.getString("version_path")); 
				}
			}
		
		} catch (Exception e) {
			System.out.println("配置文件异常信息>>>>" + "\n" + e.getMessage());
			return null;
		}

		return model;
	}

	public ArrayList<AreasModel> getAreas(String code) {

		ArrayList<AreasModel> list = null;
		try {// 测试通过
			 
			String str = GetData.GetAreaCode(code);
		 
			JSONArray jsonArray = getJsonArray(str, "Areas");
//			System.out.println("7>>地区信息>>>>" + "\n" + jsonArray);
			if (jsonArray != null) {
				list = new ArrayList<AreasModel>();				
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject json = jsonArray.getJSONObject(i);
					ChannelsModel adObj = new ChannelsModel();
					if (json != null) {
						AreasModel model = new AreasModel(); 
						model.setArea_ID(json.getString("Area_ID"));
						model.setArea_Name(json.getString("Area_Name"));
						model.setArea_Code(json.getString("Area_Code"));
						model.setParent_ID(json.getString("Parent_ID"));

						list.add(i, model);
					}
				}
			}
		} catch (Exception e) {
			System.out.println("地区异常信息>>>>" + "/n" + e.getMessage());
			return null;
		}

		return list;
	}

	public ArrayList<ChannelsModel> getChannels(String code) {
		ArrayList<ChannelsModel> list = null;
		try {// 测试通过
			String str = GetData.GetChannel(code);

			JSONArray jsonArray = getJsonArray(str, "Channels");
//			System.out.println("8>>频道信息>>>>" + "\n" + jsonArray);
			if (jsonArray != null) {
				list = new ArrayList<ChannelsModel>();			
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject json = jsonArray.getJSONObject(i);
					ChannelsModel adObj = new ChannelsModel();
					if (json != null) {
						ChannelsModel model = new ChannelsModel();
						model.setChannel_ID(json.getString("Channel_ID"));
						model.setChannel_Name(json.getString("Channel_Name"));
						model.setChannel_Price(json.getString("Channel_Price"));
						model.setChannel_Unit(json.getString("Channel_Unit"));
						model.setChannel_Status(json
								.getString("Channel_Status"));
						model.setDealLine_Date(json.getString("DealLine_Date"));
						model.setChannel_Order(json.getString("Channel_Order"));
						model.setOperator_ID(json.getString("Operator_ID"));
						model.setCreate_Date(json.getString("Create_Date"));
						list.add(i, model);
					}
				}
			}
		} catch (Exception e) {
			System.out.println("8>>频道异常信息>>>>" + "/n" + e.getMessage());
			return null;
		}

		return list;
	}

	// 公共方法，获取JSONArray对象，解析Json结构的“data”节点
	private JSONArray getJsonArray(String content, String tag) {
		JSONArray jsArray = null;
		try {
			if (content != null) {
				JSONObject jsObj = new JSONObject(content);
				if (jsObj != null && jsObj.has(tag)) {
					jsArray = jsObj.getJSONArray(tag);
				}
			}
		} catch (Exception e) {
			return null;
		}
		return jsArray;
	}

}